/**
 *
 */
package com.ebt.m.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.ebt.m.data.entity.DBConstant;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.DataUtils;
import com.ebt.m.utils.EBTInit;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ebt.db管理类
 *
 * @author Damon.Han Sqlite简单数据库操作类
 */
public class DatabaseManager {
    private Context context = null;
    private SQLiteDatabase sqliteDatabase = null;

    private AtomicInteger mOpenCounter = new AtomicInteger();
    private Cursor cursor = null;
    private static DatabaseManager dbManager;
    DataUtils du = null;// 数据库工具类


    /**
     * 构造器
     *
     * @param context --上下文
     */
    private DatabaseManager(Context context) {
        this.context = context;
        du = new DataUtils();
    }

    /**
     * 静态方法生成自身实例
     *
     * @param context
     * @return
     */
    public static synchronized DatabaseManager getInstance(Context context) {
        if (null == dbManager) {
            dbManager = new DatabaseManager(context);
        }
        return dbManager;
    }

    public synchronized SQLiteDatabase getSqliteDatabase() {
        return sqliteDatabase;
    }

    /**
     * 打开数据库
     */
    public synchronized SQLiteDatabase open() {
        // sqliteDatabase = getReadableDatabase();// 打开本地数据库
        File file = new File(ConfigData.DATABASE);
        if (!file.exists()) {
            EBTInit.copyDB(context);
        }
        if (sqliteDatabase == null || !sqliteDatabase.isOpen()) {//只有数据库未打开的时候才去打开。
            // new LogProvider(DatabaseManager.class).log("打开ebt数据库");
            sqliteDatabase = SQLiteDatabase.openOrCreateDatabase(file, null);// 打开数据库
            if (!sqliteDatabase.isReadOnly()) {
                // Enable foreign key constraints
                sqliteDatabase.execSQL("PRAGMA foreign_keys=ON;");
            }
        }

        mOpenCounter.incrementAndGet();
        return sqliteDatabase;

//		new LogProvider(DatabaseManager.class).log("----------sqliteDatabase.isOpen() is "+sqliteDatabase.isOpen());
    }

    /**
     * 关闭数据库
     */
    public synchronized void close() {
        /*if (mOpenCounter.decrementAndGet() == 0) {//只有数据库1个打开连接的时候才关闭数据库。
            if (null != cursor) {
				cursor.close();
			}
			if (null != sqliteDatabase) {
				sqliteDatabase.close();
			}
		}*/

    }

    public void closeCompetely() {
        if (null != cursor) {
            cursor.close();
        }
        if (null != sqliteDatabase) {
            sqliteDatabase.close();
        }
        mOpenCounter.set(0);
    }

    /**
     * 判断数据库是否已经打开
     */
    public boolean isOpen() {
        if (sqliteDatabase != null && sqliteDatabase.isOpen()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取数据库版本
     *
     * @return
     */
    public int getDbVersion() {
        open();
        int version = sqliteDatabase.getVersion();
        close();
        return version;
    }

    /**
     * 设置数据库版本
     *
     * @param version
     */
    public synchronized void setDbVersion(int version) {
        open();
        sqliteDatabase.beginTransaction();
        try {
            sqliteDatabase.setVersion(version);
            sqliteDatabase.setTransactionSuccessful();
        } finally {
            sqliteDatabase.endTransaction();
            close();
        }
    }


    /**
     * 使用ContentValues作为数据源插入一条数据
     *
     * @param table          --表名
     * @param nullColumnHack --null值
     * @param values         -- 插入的数据ContentValues(键值对)
     * @return ID
     */
    public long insert(String table, String nullColumnHack, ContentValues values) {

        try {
            return sqliteDatabase.insert(table, nullColumnHack, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 使用对象作为数据源插入一条数据
     *
     * @param table          --表名
     * @param nullColumnHack --null值
     * @param object         -- 包装要插入的数据(对象)
     * @return ID
     */
    public long insert(String table, String nullColumnHack, Object object) {
        try {
            ContentValues cv = du.getContentValues(object);
            return insert(table, nullColumnHack, cv);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 使用对象作为数据源插入一条数据
     *
     * @param table          --表名
     * @param nullColumnHack --null值
     * @param object         -- 包装要插入的数据(对象)
     * @return ID
     */
    public long insertWithChangeStatus(String table, String nullColumnHack, Object object) {
        try {
            ContentValues cv = du.getContentValues(object);
            cv.remove(DBConstant.COLUMN_CHANGE_STATUS);
            cv.put(DBConstant.COLUMN_CHANGE_STATUS, DBConstant.COLUMN_CHANGE_STATUS_ADD);
            return insert(table, nullColumnHack, cv);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 删除数据
     *
     * @param tableName 表名
     * @param key       数据库的字段
     * @param id        传入的值
     * @return 返回删除数量
     */
    public long delete(String tableName, String key, long id) {
        long num = -1;
        try {
            num = sqliteDatabase.delete(tableName, key + " = " + id, null);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("EBT-delete", "删除失败");
        }
        return num;
    }

    /**
     * 删除数据
     *
     * @param tableName 表名
     * @param key       数据库的字段
     * @param value     传入的值
     * @return 返回删除数量
     */
    public long deleteByKeyAndValue(String tableName, String key, String value) {
        long num = -1;
        try {
            num = sqliteDatabase.delete(tableName, key + " = '" + value + "'", null);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("EBT-delete", "删除失败");
        }
        return num;
    }

    /**
     * 根据Id获得数据集
     *
     * @param table   表名
     * @param key     键
     * @param id      值
     * @param columns 返回哪些列--如果返回全部则置null
     * @return Cursor
     */
    public Cursor findById(String table, String key, int id, String[] columns) {
        return sqliteDatabase.query(table, columns, key + " = " + id, null, null, null, null);
    }

    /**
     * 根据Id获得对象
     *
     * @param table   表名
     * @param key     键
     * @param id      值
     * @param columns 返回哪些列--如果返回全部则置null
     * @return Cursor
     */
    public <T> T findById(String table, String key, long id, String[] columns, T entity) {
        Cursor c = sqliteDatabase.query(table, columns, key + " = " + id, null, null, null, null);
        try {
            if (c.moveToNext()) {
                T en = du.getEntity(c, entity);
                return en;
            } else {
                return null;
            }
        } finally {
            c.close();
        }

    }

    /**
     * 返回全部数据集
     *
     * @param table   表名
     * @param columns 列名的集合
     * @return
     */
    public Cursor findAll(String table, String[] columns) {

        cursor = sqliteDatabase.query(table, columns, null, null, null, null, null);
        cursor.moveToFirst();
        return cursor;
    }

    public <T> List<T> findAll(String tableName, String[] columns, T entity) {
        List<T> entities = new ArrayList<T>();
        cursor = sqliteDatabase.query(tableName, columns, null, null, null, null, null);

        try {
            while (null != cursor && cursor.moveToNext()) {
                T obj = (T) entity.getClass().newInstance();
                du.getEntity(cursor, obj);
                entities.add(obj);
            }
            return entities;
        } catch (Exception e) {
            e.printStackTrace();
            return entities;
        }

    }

    /**
     * 返回所有数据集-排序
     *
     * @param table
     * @param columns
     * @param orderByString 排序
     * @return
     */
    public Cursor findAll(String table, String[] columns, String orderByString) {

        cursor = sqliteDatabase.query(table, columns, null, null, null, null, orderByString);
        cursor.moveToFirst();
        return cursor;
    }

    /**
     * 返回所有对象
     *
     * @param table
     * @param columns
     * @param orderByString 排序
     * @return
     */
    public <T> List<T> findAll(String table, String[] columns, String orderByString, T entity) {
        List<T> entities = new ArrayList<T>();
        cursor = sqliteDatabase.query(table, columns, null, null, null, null, orderByString);
        if (null != cursor && cursor.getCount() > 0) {
            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToPosition(i);
                T obj;
                try {
                    obj = (T) entity.getClass().newInstance();
                    entities.add(du.getEntity(cursor, obj));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return entities;

    }

    /**
     * 根据传入参数返回结果集
     *
     * @param tableName   表名
     * @param names       参数名称集合
     * @param values      参数值集合
     * @param columns     返回列集合
     * @param orderColumn 排序字符串
     * @param limit       返回指定条数
     * @return List结果集
     * @throws Exception
     */
    public <T> List<T> find(String tableName, String[] names, String[] values, String[] columns, String orderColumn, String limit, T entity) throws Exception {
        List<T> entities = new ArrayList<T>();// 返回的结果集
        try {
            StringBuffer selection = new StringBuffer();
            for (int i = 0; i < names.length; i++) {
                selection.append(names[i]);
                selection.append(" = ?");
                if (i != names.length - 1) {
                    selection.append(",");
                }
            }
            if (null != cursor && cursor.getCount() > 0) {
                cursor = sqliteDatabase.query(true, tableName, columns, selection.toString(), values, null, null, orderColumn, limit);
                cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++) {
                    cursor.moveToPosition(i);
                    T obj;
                    try {
                        obj = (T) entity.getClass().newInstance();
                        entities.add(du.getEntity(cursor, obj));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return entities;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 根据传入参数返回结果集
     *
     * @param tableName   表名
     * @param names       参数名称集合
     * @param values      参数值集合
     * @param columns     返回列集合
     * @param orderColumn 排序字符串
     * @param limit       返回指定条数
     * @return Cursor结果集
     * @throws Exception
     */
    public Cursor find(String tableName, String[] names, String[] values, String[] columns, String orderColumn, String limit) throws Exception {
        try {
            StringBuffer selection = new StringBuffer();
            for (int i = 0; i < names.length; i++) {
                selection.append(names[i]);
                selection.append(" = ?");
                if (i != names.length - 1) {
                    selection.append(",");
                }
            }
            cursor = sqliteDatabase.query(true, tableName, columns, selection.toString(), values, null, null, orderColumn, limit);
            cursor.moveToFirst();
            return cursor;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * @param tableName 表名
     * @param names     参数名字集合
     * @param values    参数值集合
     * @param args      要更新的内容
     * @return trueORfalse
     * @throws Exception
     */
    public boolean udpate(String tableName, String[] names, String[] values, ContentValues args) {
        try {
            StringBuffer selection = new StringBuffer();
            for (int i = 0; i < names.length; i++) {
                selection.append(names[i]);
                selection.append(" = ?");
                if (i != names.length - 1) {
                    selection.append(",");
                }
            }
            return sqliteDatabase.update(tableName, args, selection.toString(), values) > 0;
        } catch (Exception e) {
            Log.e("EBT-db", "更新失败\n" + e.getMessage());
        }
        return false;
    }

    /**
     * 更新单个对象
     *
     * @param tableName 表名
     * @param names     参数名字集合
     * @param values    参数值集合,由参数名和参数值组成whereClause
     * @param obj       要更新的内容
     * @return trueORfalse
     * @throws Exception
     */
    public boolean update(String tableName, String[] names, String[] values, Object obj) {
        ContentValues cv = du.getContentValues(obj);
        try {
            StringBuffer selection = new StringBuffer();
            for (int i = 0; i < names.length; i++) {
                selection.append(names[i]);
                selection.append(" = ?");
                if (i != names.length - 1) {
                    selection.append(",");
                }
            }
            return sqliteDatabase.update(tableName, cv, selection.toString(), values) > 0;
        } catch (Exception e) {
            Log.e("EBT-db", "更新失败\n" + e.getMessage());
        }
        return false;
    }

    /**
     * 更新单个对象，并考虑changestatus情况：
     * 1.当原来的changestatus为add时，此时update照样update，不过changestatus不变
     * 2.当原来的changestatus为其它值时，此时需要更改changestatus列为edit
     *
     * @param tableName 表名
     * @param names     参数名字集合
     * @param values    参数值集合
     * @param obj       要更新的内容
     * @return trueORfalse
     */
    public int updateWithChangeStatus(String tableName, String[] names, String[] values, Object obj) {
        ContentValues cv = null;
        if (obj instanceof ContentValues) {
            cv = (ContentValues) obj;
        } else {
            cv = du.getContentValues(obj);
        }

        try {
            StringBuffer selection = new StringBuffer();
            for (int i = 0; i < names.length; i++) {
                selection.append(names[i]);
                selection.append(" = ?");
                selection.append(" and ");
            }
            StringBuffer selection1 = new StringBuffer(selection);
            String sql1 = selection1.append(DBConstant.COLUMN_CHANGE_STATUS).append(" = " + DBConstant.COLUMN_CHANGE_STATUS_ADD).toString();
            cv.remove(DBConstant.COLUMN_CHANGE_STATUS);
            int ret1 = sqliteDatabase.update(tableName, cv, sql1, values);
            if (ret1 > 0) {
                return ret1;
            }

            StringBuffer selection2 = new StringBuffer(selection);
            String sql2 = selection2.append(DBConstant.COLUMN_CHANGE_STATUS).append(" <> " + DBConstant.COLUMN_CHANGE_STATUS_DELETE).toString();
            cv.put(DBConstant.COLUMN_CHANGE_STATUS, DBConstant.COLUMN_CHANGE_STATUS_EDIT);
            int ret2 = sqliteDatabase.update(tableName, cv, sql2, values);
            return ret2;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("EBT-db", "更新失败\n" + e.getMessage());
            return -1;
        }
    }

    /**
     * Convenience method for updating rows in the database.
     *
     * @param table       the table to update in
     * @param values      a map from column names to new column values. null is a valid
     *                    value that will be translated to NULL.
     * @param whereClause the optional WHERE clause to apply when updating. Passing null
     *                    will update all rows.
     * @return the number of rows affected
     */
    public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
        return sqliteDatabase.update(table, values, whereClause, whereArgs);
    }

    /**
     * Convenience method for updating rows in the database.
     *
     * @param tableName   the table to update in
     * @param columnName  the name of the column.
     * @param columnValue the value of the column. the value type is string
     * @return the number of rows affected
     */
    public int updateColumn(String tableName, String columnName, String columnValue, String uuid) {
        ContentValues values = new ContentValues();
        values.put(columnName, columnValue);
        return sqliteDatabase.update(tableName, values, "uuid='" + uuid + "'", null);
    }

    /**
     * Convenience method for updating rows in the database.
     *
     * @param tableName   the table to update in
     * @param columnName  the name of the column.
     * @param columnValue the value of the column. the value type is integer
     * @return the number of rows affected
     */
    public int updateColumn(String tableName, String columnName, Integer columnValue, String uuid) {
        ContentValues values = new ContentValues();
        values.put(columnName, columnValue);
        return sqliteDatabase.update(tableName, values, "uuid='" + uuid + "'", null);
    }

    /**
     * Convenience method for updating rows in the database.
     *
     * @param tableName   the table to update in
     * @param columnName  the name of the column.
     * @param columnValue the value of the column. the value type is integer
     * @return the number of rows affected
     */
    public int updateColumnByWhereClause(String tableName, String columnName, Integer columnValue, String whereClause) {
        ContentValues values = new ContentValues();
        values.put(columnName, columnValue);
        return sqliteDatabase.update(tableName, values, whereClause, null);
    }

    /**
     * Convenience method for deleting rows in the database.
     *
     * @param table       the table to delete from
     * @param whereClause the optional WHERE clause to apply when deleting. Passing null
     *                    will delete all rows.
     * @return the number of rows affected if a whereClause is passed in, 0
     * otherwise. To remove all rows and get a count pass "1" as the
     * whereClause.
     */
    public int delete(String table, String whereClause, String[] whereArgs) {
        return sqliteDatabase.delete(table, whereClause, whereArgs);
    }

    /**
     * 更新某一字段值
     *
     * @param table
     * @param colName
     * @param colValue
     * @param whereClause
     * @param whereArgs
     */
    public void rawUpdate(String table, String colName, Object colValue, String whereClause, Object[] whereArgs) {
        StringBuilder sql = new StringBuilder(120);
        sql.append("UPDATE ").append(table).append(" SET ");
        sql.append(colName).append(" = ").append(colValue);

        if (!TextUtils.isEmpty(whereClause)) {
            sql.append(" WHERE ");
            sql.append(whereClause);
        }
        sqliteDatabase.execSQL(sql.toString(), whereArgs);
    }

    /**
     * 直接执行sql
     *
     * @param sql
     */
    public void executeSql(String sql) {
        sqliteDatabase.execSQL(sql);
    }

    public void executeSql(String sql, Object[] bindArgs) {
        sqliteDatabase.execSQL(sql, bindArgs);
    }

    /**
     * 开始事务
     */
    public void beginTransaction() {
        sqliteDatabase.beginTransaction();
    }

    /**
     * 提交事务及结束事务
     */
    public void commit() {
        sqliteDatabase.setTransactionSuccessful();
        sqliteDatabase.endTransaction();
    }

    /**
     * 调用此方法会在执行到endTransaction() 时提交当前事务，如果不调用此方法会回滚事务
     */
    public void setTransactionSuccessful() {
        sqliteDatabase.setTransactionSuccessful();
    }

    /**
     * 由事务的标志决定是否提交
     */
    public void endTransaction() {
        sqliteDatabase.endTransaction();
    }

    /**
     * 回滚事务
     */
    public void rollback() {
        sqliteDatabase.endTransaction();
    }

    /**
     * 执行带问号的sql获得数量
     *
     * @param sql
     * @return
     */
    public Long getCount(String sql) {
        Cursor c = sqliteDatabase.rawQuery(sql, null);
        c.moveToFirst();
        long count = c.getLong(0);
        c.close();
        return count;
    }

    /**
     * 通过SQL语句获得对应的VO。 注意：Cursor的字段名或者别名一定要和VO的成员名一样
     *
     * @param <T>
     * @param sql
     * @return
     */
    @SuppressWarnings("rawtypes")
    public <T> T sql2VO(String sql, T entity) {
        Cursor c = sqliteDatabase.rawQuery(sql, null);
        return cursor2VO(c, entity);
    }

    /**
     * 通过SQL语句获得对应的VO。注意：Cursor的字段名或者别名一定要和VO的成员名一样
     *
     * @param sql
     * @param selectionArgs
     * @return
     */
    @SuppressWarnings("rawtypes")
    public <T> T sql2VO(String sql, String[] selectionArgs, T entity) {
        Cursor c = sqliteDatabase.rawQuery(sql, selectionArgs);
        return cursor2VO(c, entity);
    }

    /**
     * 通过SQL语句获得对应的VO的List。注意：Cursor的字段名或者别名一定要和VO的成员名一样
     */
    @SuppressWarnings("rawtypes")
    public <T> List<T> sql2VOList(String sql, T entity) {
        Cursor c = sqliteDatabase.rawQuery(sql, null);
        return cursor2VOList(c, entity);
    }

    /**
     * 通过SQL语句获得对应的VO的List。注意：Cursor的字段名或者别名一定要和VO的成员名一样
     */
    @SuppressWarnings("rawtypes")
    public <T> List<T> sql2VOListOverride(String sql, T entity) {
        Cursor c = sqliteDatabase.rawQuery(sql, null);
        return cursor2VOListOverride(c, entity);
    }

    /**
     * 通过SQL语句获得对应的VO的List。注意：Cursor的字段名或者别名一定要和VO的成员名一样
     *
     * @param sql
     * @param selectionArgs
     * @return
     */
    @SuppressWarnings("rawtypes")
    public <T> List<T> sql2VOList(String sql, String[] selectionArgs, T entity) {
        Cursor c = sqliteDatabase.rawQuery(sql, selectionArgs);
        return cursor2VOList(c, entity);
    }

    /**
     * 通过Cursor转换成对应的VO。注意：Cursor里的字段名（可用别名）必须要和VO的属性名一致
     *
     * @param c
     * @param entity
     * @return
     */
    @SuppressWarnings({"rawtypes", "unused"})
    public <T> T cursor2VO(Cursor c, T entity) {
        if (c == null) {
            return null;
        }
        T en = null;
        try {
            if (c.moveToNext()) {
                en = du.getEntity(c, entity);
            }
            return en;
        } catch (Exception e) {
            System.out.println(e);
            return en;
        } finally {
            c.close();
        }
    }

    /**
     * 通过Cursor转换成对应的VO集合。注意：Cursor里的字段名（可用别名）必须要和VO的属性名一致
     *
     * @param c
     * @param entity
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public <T> List<T> cursor2VOList(Cursor c, T entity) {
        if (c == null) {
            return null;
        }
        List list = new ArrayList();
        Object obj;
        try {
            while (c.moveToNext()) {
                obj = (T) entity.getClass().newInstance();
                list.add(du.getEntity(c, obj));

                // obj = du.getEntity(c, entity);
                // System.out.println(obj);
                // list.add(obj);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR @：cursor2VOList");
            return null;
        } finally {
            c.close();
        }
    }

    /**
     * 通过Cursor转换成对应的VO集合。注意：Cursor里的字段名（可用别名）必须要和VO的属性名一致
     *
     * @param c
     * @param entity
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public <T> List<T> cursor2VOListOverride(Cursor c, T entity) {
        if (c == null) {
            return null;
        }
        List list = new ArrayList();
        Object obj;
        try {
            while (c.moveToNext()) {
                obj = (T) entity.getClass().newInstance();
                list.add(du.getEntityOverride(c, obj));
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR @：cursor2VOListOverride");
            return null;
        } finally {
            c.close();
        }
    }

    /**
     * 把值设置进类属性里
     *
     * @param c
     * @param clazz
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    private static Object setValues2Fields(Cursor c, Class clazz) throws Exception {
        String[] columnNames = c.getColumnNames();// 字段数组
        Object obj = clazz.newInstance();
        Field[] fields = clazz.getFields();

        for (Field _field : fields) {
            Class<? extends Object> typeClass = _field.getType();// 属性类型
            for (int j = 0; j < columnNames.length; j++) {
                String columnName = columnNames[j];
                typeClass = getBasicClass(typeClass);
                boolean isBasicType = isBasicType(typeClass);

                if (isBasicType) {
                    if (columnName.equalsIgnoreCase(_field.getName())) {// 是基本类型
                        String _str = c.getString(c.getColumnIndex(columnName));
                        if (_str == null) {
                            break;
                        }
                        _str = _str == null ? "" : _str;
                        Constructor<? extends Object> cons = typeClass.getConstructor(String.class);
                        Object attribute = cons.newInstance(_str);
                        _field.setAccessible(true);
                        _field.set(obj, attribute);
                        break;
                    }
                } else {
                    Object obj2 = setValues2Fields(c, typeClass);// 递归
                    _field.set(obj, obj2);
                    break;
                }

            }
        }
        return obj;
    }

    /**
     * 判断是不是基本类型
     *
     * @param typeClass
     * @return
     */
    @SuppressWarnings("rawtypes")
    private static boolean isBasicType(Class typeClass) {
        if (typeClass.equals(Integer.class) || typeClass.equals(Long.class) || typeClass.equals(Float.class) || typeClass.equals(Double.class) || typeClass.equals(Boolean.class) || typeClass.equals(Byte.class) || typeClass.equals(Short.class) || typeClass.equals(String.class)) {

            return true;

        } else {
            return false;
        }
    }

    /**
     * 获得包装类
     *
     * @param typeClass
     * @return
     */
    @SuppressWarnings("all")
    public static Class<? extends Object> getBasicClass(Class typeClass) {
        Class _class = basicMap.get(typeClass);
        if (_class == null)
            _class = typeClass;
        return _class;
    }

    @SuppressWarnings("rawtypes")
    private static Map<Class, Class> basicMap = new HashMap<Class, Class>();

    static {
        basicMap.put(int.class, Integer.class);
        basicMap.put(long.class, Long.class);
        basicMap.put(float.class, Float.class);
        basicMap.put(double.class, Double.class);
        basicMap.put(boolean.class, Boolean.class);
        basicMap.put(byte.class, Byte.class);
        basicMap.put(short.class, Short.class);
    }

	/*
     * 获取当前表的id的序列号
	 * 
	 * @param table 表名
	 * 
	 * @ return 主键的序列号
	 */

    public long getTableSquence(String table) {
        long seq = 0;
        StringBuffer sql = new StringBuffer();
        sql.append("select  seq from sqlite_sequence WHERE name = '").append(table).append("'");
        Cursor c = sqliteDatabase.rawQuery(sql.toString(), null);
        c.moveToFirst();
        if (c.moveToFirst()) {
            seq = c.getLong(0);

        }
        return seq;
    }

    public Cursor rawQuery(String sql, String[] selectionArgs) {
        return sqliteDatabase.rawQuery(sql, selectionArgs);
    }

    public Cursor query(String table) {
        return query(table, null);
    }

    public Cursor query(String table, long id) {
        return query(table, null, " id=?", new String[]{id + ""});
    }

    public Cursor query(String table, String column, long value) {
        return query(table, null, column + "=?", new String[]{value + ""}, null);
    }

    public Cursor query(String table, String column, long value, String orderBy) {
        return query(table, null, column + "=?", new String[]{value + ""}, orderBy);
    }

    public Cursor query(String table, String[] columns) {
        return query(table, columns, null, null, null);
    }

    public Cursor queryWithOrder(String table, String orderBy) {
        return query(table, null, null, null, orderBy);
    }

    public Cursor query(String table, String[] columns, String selection, String[] selectionArgs) {
        return query(table, columns, selection, selectionArgs, null);
    }

    public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String orderBy) {
        return sqliteDatabase.query(table, columns, selection, selectionArgs, null, null, orderBy);
    }

    public Cursor query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String orderBy) {
        return sqliteDatabase.query(distinct, table, columns, selection, selectionArgs, null, null, orderBy, null);

    }

    public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String orderBy, String limit) {
        return sqliteDatabase.query(table, columns, selection, selectionArgs, null, null, orderBy, limit);
    }

    /**
     * 根据主键删除
     *
     * @param table 表名
     * @param key   主键值
     * @return
     */
    public int deleteByKey(String table, long key) {
        return sqliteDatabase.delete(table, " id=?", new String[]{key + ""});
    }

    /**
     * 根据主键删除
     *
     * @param table   表名
     * @param keyUUID uuid主键值
     * @return
     */
    public int deleteByKeyUUID(String table, String keyUUID) {
        return sqliteDatabase.delete(table, " uuid=?", new String[]{keyUUID});
    }

    /**
     * 获取count
     *
     * @param table
     * @param selection
     * @param selectionArgs
     * @return
     */
    public Long getCount(String table, String selection, String[] selectionArgs) {
        long count = 0;
        StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM ");
        sql.append(table).append(" WHERE ").append(selection);
        Cursor c = sqliteDatabase.rawQuery(sql.toString(), selectionArgs);
        c.moveToFirst();
        count = c.getLong(0);
        c.close();
        return count;
    }

	/*
     * 获取某列最大值(int 或者long类型)
	 * 
	 * @param table 表名
	 * 
	 * @param sequenceColumnName 列名
	 * 
	 * @ return 最大值
	 */

    public long getMaxSquence(String table, String columnName) {
        long seq = 0;
        StringBuffer sql = new StringBuffer();
        sql.append("select max(").append(columnName).append(") from ").append(table);
        Cursor c = sqliteDatabase.rawQuery(sql.toString(), null);
        c.moveToFirst();
        if (c.moveToFirst()) {
            seq = c.getLong(0);
        }
        return seq;
    }

}
